﻿using Dapper;
using InventoryIssue.API.Read.Application.Command.Allocate;
using InventoryIssue.Domain;
using InventoryIssue.ErrorCode;
using InventoryIssue.Infrastructrue.Implement;
using MediatR;
using System.Text;

namespace InventoryIssue.API.Read.Application.Handler.Allocate
{
    public class GetAllocateOperationLogHandler : IRequestHandler<GetAllocateOperationLogCommand, APIPaging<OperationLog>>
    {
        private readonly DatabaseContext db;

        public GetAllocateOperationLogHandler(DatabaseContext db)
        {
            this.db = db;
        }

        public async Task<APIPaging<OperationLog>> Handle(GetAllocateOperationLogCommand request, CancellationToken cancellationToken)
        {
            APIPaging<OperationLog> result = new APIPaging<OperationLog>();
            StringBuilder sql = new StringBuilder();
            StringBuilder countSql = new StringBuilder();
            
            sql.Append(@"
                SELECT
                    Id,
                    Operator,
                    AllocateId,
                    OperationType,
                    OperationContent,
                    CreateTime
                FROM
                    operationlog
                WHERE
                    IsDel = 0
            ");
            
            countSql.Append(@"
                SELECT
                    COUNT(Id)
                FROM
                    operationlog
                WHERE
                    IsDel = 0
            ");

            // 根据操作类型筛选
            if (!string.IsNullOrEmpty(request.OperationType))
            {
                sql.Append(" AND OperationType LIKE @OperationType");
                countSql.Append(" AND OperationType LIKE @OperationType");
            }

            // 根据操作人筛选
            if (!string.IsNullOrEmpty(request.Operator))
            {
                sql.Append(" AND Operator LIKE @Operator");
                countSql.Append(" AND Operator LIKE @Operator");
            }

            // 根据操作时间筛选
            if (request.OperationTime.HasValue)
            {
                sql.Append(" AND DATE(CreateTime) = @OperationTime");
                countSql.Append(" AND DATE(CreateTime) = @OperationTime");
            }

            // 根据调拨单号筛选
            if (!string.IsNullOrEmpty(request.AllocateId))
            {
                sql.Append(" AND AllocateId LIKE @AllocateId");
                countSql.Append(" AND AllocateId LIKE @AllocateId");
            }

            // 按操作时间倒序排列
            sql.Append(" ORDER BY CreateTime DESC LIMIT @PageSize OFFSET @offset");

            var parameters = new
            {
                OperationType = $"%{request.OperationType}%",
                Operator = $"%{request.Operator}%",
                OperationTime = request.OperationTime?.ToString("yyyy-MM-dd"),
                AllocateId = $"%{request.AllocateId}%",
                PageSize = request.PageSize,
                offset = (request.PageIndex - 1) * request.PageSize
            };

            var pageDatas = await db.DapperConnection.QueryAsync<OperationLog>(sql.ToString(), parameters);
            int totalCount = await db.DapperConnection.ExecuteScalarAsync<int>(countSql.ToString(), parameters);
            int totalPage = (int)Math.Ceiling(totalCount / (double)request.PageSize);

            result.Message = "查询成功";
            result.Code = APIEnum.Ok;
            result.TotalPage = totalPage;
            result.TotalCount = totalCount;
            result.PageDatas = pageDatas.ToList();

            return result;
        }
    }
}
